package handler

import (
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/julienschmidt/httprouter"
)

const (
	VIDEO_DIR       = "./videos/"
	MAX_UPLOAD_SIZE = 1024 * 1024 * 50 //50MB
)

func TestPageHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	t, _ := template.ParseFiles("./videos/upload.html")

	t.Execute(w, nil)
}

// 可以自己变成二进制流 然后进行传输 可以控制带宽 和 速度 但是麻烦
func StreamHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	vid := p.ByName("vid-id")
	vl := VIDEO_DIR + vid

	video, err := os.Open(vl)
	if err != nil {
		log.Printf("Error when try to open file: %v", err)
		SendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
		return
	}

	w.Header().Set("Content-Type", "video/mp4")
	// 高速browser 接下来的数据按照mp4解析
	http.ServeContent(w, r, "", time.Now(), video)

	defer video.Close()
}

func UploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// ioreader最大能读取的文件大小
	r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)
	// 解析谓multipartForm格式
	if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
		SendErrorResponse(w, http.StatusBadRequest, "File is too big")
		return
	}

	file, _, err := r.FormFile("file")
	if err != nil {
		log.Printf("Error when try to get file: %v", err)
		SendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
		return
	}

	data, err := io.ReadAll(file)
	if err != nil {
		log.Printf("Read file error: %v", err)
		SendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
	}

	fn := p.ByName("vid-id")
	err = os.WriteFile(VIDEO_DIR+fn, data, 0666)
	if err != nil {
		log.Printf("Write file error: %v", err)
		SendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
		return
	}

	w.WriteHeader(http.StatusCreated)
	io.WriteString(w, "Uploaded successfully")
}

func TestHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	vl := "/home/lizhi/goprogram/smedia/streamer/一分钟精通如何使用同步空间_副本.mp4"

	video, err := os.Open(vl)
	if err != nil {
		log.Printf("Error when try to open file: %v", err)
		SendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
		return
	}

	w.Header().Set("Content-Type", "video/mp4")
	// 高速browser 接下来的数据按照mp4解析
	http.ServeContent(w, r, "", time.Now(), video)

	defer video.Close()
}
